document.addEventListener('DOMContentLoaded', function() {
    // 初始化图表实例
    const charts = initializeCharts();
    
    // 绑定表单提交事件
    document.getElementById('statsForm').addEventListener('submit', function(e) {
        e.preventDefault();
        generateStatistics();
    });
    
    // 生成默认统计数据
    generateStatistics();
    
    // 初始化所有图表
    function initializeCharts() {
        return {
            hourly: echarts.init(document.getElementById('hourlyChart')),
            weekday: echarts.init(document.getElementById('weekdayChart')),
            weekend: echarts.init(document.getElementById('weekendChart')),
            usMarket: echarts.init(document.getElementById('usMarketChart')),
            candleType: echarts.init(document.getElementById('candleTypeChart')),
            consecutive: echarts.init(document.getElementById('consecutiveChart')),
            volumePrice: echarts.init(document.getElementById('volumePriceChart')),
            volatility: echarts.init(document.getElementById('volatilityChart')),
            correlation: echarts.init(document.getElementById('correlationChart')),
            futureDirection: echarts.init(document.getElementById('futureDirectionChart')),
            similarity: echarts.init(document.getElementById('similarityChart')),
            predictionModel: echarts.init(document.getElementById('predictionModelContainer'))
        };
    }
    
    // 生成统计数据
    function generateStatistics() {
        const symbol = document.getElementById('symbol').value;
        const interval = document.getElementById('interval').value;
        const timeRange = document.getElementById('timeRange').value;
        
        // 显示加载中状态
        Object.values(charts).forEach(chart => {
            chart.showLoading({
                text: '数据加载中...',
                color: '#007bff',
                textColor: '#000',
                maskColor: 'rgba(255, 255, 255, 0.8)'
            });
        });
        
        // 从API获取实际数据
        fetch(`/api/enhanced_stats?symbol=${symbol}&interval=${interval}&range=${timeRange}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('API请求失败: ' + response.statusText);
                }
                return response.json();
            })
            .then(data => {
                console.log("API返回数据:", data);
                
                // 更新各个图表
                updateTimeAnalysisCharts(data);
                updatePatternAnalysisCharts(data);
                updateMultiDimensionalCharts(data);
                updatePredictionCharts(data);
                
                // 隐藏加载状态
                Object.values(charts).forEach(chart => {
                    chart.hideLoading();
                });
            })
            .catch(error => {
                console.error('获取数据失败:', error);
                alert('获取数据失败: ' + error.message);
                
                // 使用模拟数据作为备选
                console.log('使用模拟数据...');
                const mockData = generateMockData(symbol, interval, timeRange);
                
                updateTimeAnalysisCharts(mockData);
                updatePatternAnalysisCharts(mockData);
                updateMultiDimensionalCharts(mockData);
                updatePredictionCharts(mockData);
                
                // 隐藏加载状态
                Object.values(charts).forEach(chart => {
                    chart.hideLoading();
                });
            });
    }
    
    // 生成模拟数据（备选方案）
    function generateMockData(symbol, interval, timeRange) {
        // 小时统计数据
        const hourlyStats = Array.from({length: 24}, (_, i) => ({
            hour: i,
            avgReturn: (Math.random() * 2 - 1).toFixed(2),
            avgVolume: Math.floor(Math.random() * 1000 + 500),
            bullishPercent: (Math.random() * 30 + 40).toFixed(2)
        }));
        
        // 星期几统计数据
        const weekdayStats = Array.from({length: 7}, (_, i) => ({
            weekday: i,
            avgReturn: (Math.random() * 2 - 1).toFixed(2),
            avgVolatility: (Math.random() * 3 + 1).toFixed(2),
            bullishPercent: (Math.random() * 30 + 40).toFixed(2)
        }));
        
        // 周末vs工作日
        const weekendStats = [
            {
                is_weekend: 0,
                count: 780,
                avgReturn: 0.25,
                bullishPercent: 52.5,
                avgVolume: 850,
                avgVolatility: 2.3
            },
            {
                is_weekend: 1,
                count: 320,
                avgReturn: -0.15,
                bullishPercent: 48.2,
                avgVolume: 650,
                avgVolatility: 1.9
            }
        ];
        
        // 美股交易时间
        const usMarketStats = [
            {
                is_us_market_open: 0,
                count: 600,
                avgReturn: 0.15,
                bullishPercent: 51.3,
                avgVolume: 750,
                avgVolatility: 2.1
            },
            {
                is_us_market_open: 1,
                count: 500,
                avgReturn: 0.32,
                bullishPercent: 53.7,
                avgVolume: 900,
                avgVolatility: 2.5
            }
        ];
        
        // K线类型分布
        const candleTypeStats = [
            {
                candle_type: 'bullish',
                count: 550,
                percentage: 52.4,
                avgReturn: 1.5,
                avgVolume: 820
            },
            {
                candle_type: 'bearish',
                count: 490,
                percentage: 46.7,
                avgReturn: -1.3,
                avgVolume: 780
            },
            {
                candle_type: 'doji',
                count: 10,
                percentage: 0.9,
                avgReturn: 0.1,
                avgVolume: 400
            }
        ];
        
        return {
            symbol,
            interval,
            timeRange,
            hourlyStats,
            weekdayStats,
            weekendStats,
            usMarketStats,
            candleTypeStats,
            // 其他模拟数据...
        };
    }
    
    // 更新时间模式分析图表
    function updateTimeAnalysisCharts(data) {
        // 小时分布统计
        charts.hourly.setOption({
            title: {
                text: '24小时K线表现分布',
                left: 'center'
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            legend: {
                data: ['平均涨幅%', '平均交易量', '上涨概率%'],
                bottom: 0
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '15%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: Array.from({length: 24}, (_, i) => i)
            },
            yAxis: [
                {
                    type: 'value',
                    name: '涨幅/概率',
                    axisLabel: {
                        formatter: '{value}%'
                    }
                },
                {
                    type: 'value',
                    name: '交易量',
                    position: 'right'
                }
            ],
            series: [
                {
                    name: '平均涨幅%',
                    type: 'line',
                    data: data.hourlyStats.map(item => item.avgReturn)
                },
                {
                    name: '平均交易量',
                    type: 'bar',
                    yAxisIndex: 1,
                    data: data.hourlyStats.map(item => item.avgVolume)
                },
                {
                    name: '上涨概率%',
                    type: 'line',
                    data: data.hourlyStats.map(item => item.bullishPercent)
                }
            ]
        });
        
        // 周内日分布统计
        charts.weekday.setOption({
            title: {
                text: '周内日K线表现',
                left: 'center'
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            legend: {
                data: ['平均涨幅%', '平均波动%', '上涨概率%'],
                bottom: 0
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '15%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
            },
            yAxis: {
                type: 'value',
                axisLabel: {
                    formatter: '{value}%'
                }
            },
            series: [
                {
                    name: '平均涨幅%',
                    type: 'bar',
                    data: data.weekdayStats.map(item => item.avgReturn)
                },
                {
                    name: '平均波动%',
                    type: 'line',
                    data: data.weekdayStats.map(item => item.avgVolatility)
                },
                {
                    name: '上涨概率%',
                    type: 'line',
                    data: data.weekdayStats.map(item => item.bullishPercent)
                }
            ]
        });
        
        // 工作日vs周末对比
        const weekendLabels = ['工作日', '周末'];
        charts.weekend.setOption({
            title: {
                text: '工作日vs周末表现对比',
                left: 'center'
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            legend: {
                data: ['平均涨幅%', '上涨概率%', '平均波动%'],
                bottom: 0
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '15%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: weekendLabels
            },
            yAxis: {
                type: 'value',
                axisLabel: {
                    formatter: '{value}%'
                }
            },
            series: [
                {
                    name: '平均涨幅%',
                    type: 'bar',
                    data: data.weekendStats.map(item => parseFloat(item.avg_return.toFixed(2)))
                },
                {
                    name: '上涨概率%',
                    type: 'bar',
                    data: data.weekendStats.map(item => parseFloat(item.bullish_percent.toFixed(2)))
                },
                {
                    name: '平均波动%',
                    type: 'bar',
                    data: data.weekendStats.map(item => parseFloat(item.avg_volatility.toFixed(2)))
                }
            ]
        });
        
        // 美股交易时段表现
        const marketLabels = ['美股休市', '美股交易'];
        charts.usMarket.setOption({
            title: {
                text: '美股交易时段表现对比',
                left: 'center'
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            legend: {
                data: ['平均涨幅%', '上涨概率%', '平均波动%'],
                bottom: 0
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '15%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: marketLabels
            },
            yAxis: {
                type: 'value',
                axisLabel: {
                    formatter: '{value}%'
                }
            },
            series: [
                {
                    name: '平均涨幅%',
                    type: 'bar',
                    data: data.usMarketStats.map(item => parseFloat(item.avg_return.toFixed(2)))
                },
                {
                    name: '上涨概率%',
                    type: 'bar',
                    data: data.usMarketStats.map(item => parseFloat(item.bullish_percent.toFixed(2)))
                },
                {
                    name: '平均波动%',
                    type: 'bar',
                    data: data.usMarketStats.map(item => parseFloat(item.avg_volatility.toFixed(2)))
                }
            ]
        });
    }
    
    // 更新K线形态分析图表
    function updatePatternAnalysisCharts(data) {
        // K线类型分布
        const candleLabels = ['阳线', '阴线', '十字星'];
        const candleTypes = ['bullish', 'bearish', 'doji'];
        
        const pieData = candleTypes.map((type, index) => {
            const found = data.candleTypeStats.find(item => item.candle_type === type);
            if (found) {
                return {
                    value: parseFloat(found.percentage.toFixed(1)),
                    name: candleLabels[index]
                };
            }
            return { value: 0, name: candleLabels[index] };
        });
        
        charts.candleType.setOption({
            title: {
                text: 'K线类型分布',
                left: 'center'
            },
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'horizontal',
                bottom: 10,
                data: candleLabels
            },
            series: [
                {
                    name: 'K线类型',
                    type: 'pie',
                    radius: ['40%', '70%'],
                    avoidLabelOverlap: false,
                    itemStyle: {
                        borderRadius: 10,
                        borderColor: '#fff',
                        borderWidth: 2
                    },
                    label: {
                        show: false,
                        position: 'center'
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: '18',
                            fontWeight: 'bold'
                        }
                    },
                    labelLine: {
                        show: false
                    },
                    data: pieData
                }
            ]
        });
        
        // 连续涨跌统计
        if (data.consecutiveStats && data.consecutiveStats.stats) {
            const consecutiveData = data.consecutiveStats.stats;
            
            charts.consecutive.setOption({
                title: {
                    text: '连续涨跌统计',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    },
                    formatter: function(params) {
                        const data = params[0].data;
                        return `<div style="font-weight:bold;margin-bottom:5px">${params[0].name}次连续</div>
                                <div>上涨次数: ${data.up_count} (${data.avg_up_return}%)</div>
                                <div>下跌次数: ${data.down_count} (${data.avg_down_return}%)</div>
                                <div>总出现次数: ${data.total_count}</div>
                                <div>出现频率: ${data.frequency}%</div>`;
                    }
                },
                legend: {
                    data: ['上涨次数', '下跌次数', '平均收益率'],
                    bottom: 0
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '15%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: consecutiveData.map(item => item.consecutive_count + '次')
                },
                yAxis: [
                    {
                        type: 'value',
                        name: '次数',
                        axisLabel: {
                            formatter: '{value}'
                        }
                    },
                    {
                        type: 'value',
                        name: '收益率',
                        position: 'right',
                        axisLabel: {
                            formatter: '{value}%'
                        }
                    }
                ],
                series: [
                    {
                        name: '上涨次数',
                        type: 'bar',
                        stack: 'total',
                        itemStyle: {
                            color: '#4CAF50'
                        },
                        data: consecutiveData.map(item => ({
                            value: item.up_count,
                            up_count: item.up_count,
                            down_count: item.down_count,
                            total_count: item.total_count,
                            frequency: item.frequency,
                            avg_up_return: item.avg_up_return,
                            avg_down_return: item.avg_down_return
                        }))
                    },
                    {
                        name: '下跌次数',
                        type: 'bar',
                        stack: 'total',
                        itemStyle: {
                            color: '#F44336'
                        },
                        data: consecutiveData.map(item => ({
                            value: item.down_count,
                            up_count: item.up_count,
                            down_count: item.down_count,
                            total_count: item.total_count,
                            frequency: item.frequency,
                            avg_up_return: item.avg_up_return,
                            avg_down_return: item.avg_down_return
                        }))
                    },
                    {
                        name: '平均收益率',
                        type: 'line',
                        yAxisIndex: 1,
                        data: consecutiveData.map(item => {
                            // 计算加权平均收益率
                            if (item.total_count === 0) return 0;
                            
                            const totalWeight = item.up_count + item.down_count;
                            const weightedReturn = 
                                (item.avg_up_return * item.up_count + 
                                 item.avg_down_return * item.down_count) / totalWeight;
                                 
                            return parseFloat(weightedReturn.toFixed(2));
                        })
                    }
                ]
            });
            
            // 创建并显示连续涨跌记录表格
            createConsecutiveTable(data.consecutiveStats.recentRuns);
        }
    }
    
    // 创建连续涨跌记录表格
    function createConsecutiveTable(recentRuns) {
        if (!recentRuns || recentRuns.length === 0) return;
        
        // 获取表格容器
        const tableContainer = document.getElementById('consecutiveTableContainer');
        if (!tableContainer) return;
        
        // 清空表格容器
        tableContainer.innerHTML = '<h5 class="card-title text-center">近期连续涨跌记录</h5>';
        
        // 创建表格
        const table = document.createElement('table');
        table.className = 'table table-striped table-sm';
        
        // 创建表头
        const thead = document.createElement('thead');
        thead.innerHTML = `
            <tr>
                <th>类型</th>
                <th>连续次数</th>
                <th>开始时间</th>
                <th>结束时间</th>
                <th>价格变化</th>
                <th>收益率</th>
            </tr>
        `;
        table.appendChild(thead);
        
        // 创建表格内容
        const tbody = document.createElement('tbody');
        
        recentRuns.forEach(run => {
            const row = document.createElement('tr');
            
            // 设置行类，根据上涨/下跌类型添加不同颜色
            row.className = run.type === 'up' ? 'table-success' : 'table-danger';
            
            // 格式化日期
            const startDate = new Date(run.startTime);
            const endDate = new Date(run.endTime);
            const formatDate = (date) => {
                return date.toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit'
                });
            };
            
            // 计算价格变化
            const priceChange = run.endPrice - run.startPrice;
            
            row.innerHTML = `
                <td>${run.type === 'up' ? '上涨' : '下跌'}</td>
                <td>${run.count}次</td>
                <td>${formatDate(startDate)}</td>
                <td>${formatDate(endDate)}</td>
                <td>${priceChange > 0 ? '+' : ''}${priceChange.toFixed(2)}</td>
                <td>${run.pctChange > 0 ? '+' : ''}${run.pctChange}%</td>
            `;
            
            tbody.appendChild(row);
        });
        
        table.appendChild(tbody);
        tableContainer.appendChild(table);
    }
    
    // 更新多维交叉分析图表
    function updateMultiDimensionalCharts(data) {
        // 为简化演示，暂时留空
    }
    
    // 更新趋势预测分析图表
    function updatePredictionCharts(data) {
        // 为简化演示，暂时留空
    }
    
    // 响应窗口大小变化，调整图表尺寸
    window.addEventListener('resize', function() {
        Object.values(charts).forEach(chart => {
            chart.resize();
        });
    });
}); 